
package cn.books.bookstore.controller;

import cn.books.bookstore.entity.Book;
import cn.books.bookstore.entity.ResEnum;
import cn.books.bookstore.mapper.BookRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * BookController
 */
@RestController
@RequestMapping("/book")
@CrossOrigin
public class BookController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookRepo bookRepo;

    @DeleteMapping
    public Map deleteById(@RequestParam("id") Integer id) {
        if (bookRepo.findById(id).isPresent()) {
            LOGGER.info("delete book id={}", id);
            bookRepo.deleteById(id);
        }
        return ResEnum.SUCCESS_ENUM.setData(null).toMap();
    }

    @GetMapping("/{id}")
    public Map getById(@PathVariable("id") Integer id) {
        Optional<Book> bookOptional = bookRepo.findById(id);
        System.out.println(bookOptional.isPresent());
        if (!bookOptional.isPresent()) {
            LOGGER.info("Book [{}] not exists", id);
            return ResEnum.ERROR_ENUM.setMsg("Book [" + id + "] not exists").setData(null).toMap();
        }
        Book book = bookOptional.get();
        LOGGER.info("getbyId:" + book);
        return ResEnum.SUCCESS_ENUM.setData(book).toMap();
    }

    @GetMapping("/list/{page}/{size}")
    public Page<Book> getList(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Book> books = bookRepo.findAll(pageable);
        LOGGER.info("get all:" + books);
        return books;
    }

    @GetMapping("/all")
    public Map getAll() {
        List<Book> books = bookRepo.findAll();
        LOGGER.info("get all:" + books);
        return books != null && books.size() > 0 ? ResEnum.SUCCESS_ENUM.setData(books).toMap()
                : ResEnum.ERROR_ENUM.setData(books).toMap();
    }

    @PostMapping
    public Map saveBook(@RequestBody Book book) {
        Book res = bookRepo.save(book);
        LOGGER.info("save:" + res);
        return res != null ? ResEnum.SUCCESS_ENUM.setData(res).toMap() : ResEnum.ERROR_ENUM.setData(res).toMap();
    }

    @PutMapping
    public Map updateBook(@RequestBody Book book) {
        Book res = bookRepo.save(book);
        LOGGER.info("put:" + res);
        return res != null ? ResEnum.SUCCESS_ENUM.setData(res).toMap() : ResEnum.ERROR_ENUM.setData(res).toMap();
    }
}
